package com.frankie.weibo.miweibo.api;

import com.frankie.weibo.MiApplication;
import com.frankie.weibo.miweibo.bean.Error;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Frankie on 2016/8/16.
 */

public class WeiboHttpUtil {

    private static final String SERVER_URL = "https://api.weibo.com/2/";

    private static OkHttpClient okHttpClient;
    private static Gson gson;

    private WeiboHttpUtil(){}

    public static OkHttpClient init(){
        if(okHttpClient == null){
            synchronized (WeiboHttpUtil.class){
                if(okHttpClient == null){
                    synchronized (WeiboHttpUtil.class){
                        okHttpClient = new OkHttpClient();
                        gson = new Gson();
                    }
                }
            }
        }
        return okHttpClient;
    }

    private static Request getBuilder(String url, HashMap<String, String> params, Method method){
        url = SERVER_URL + url;
        Request.Builder builder = new Request.Builder();
        if(params == null)
            params = new HashMap<String,String>();
        params.put("access_token", MiApplication.accessToken.getToken());

        //组装参数
        Set<String> keys = params.keySet();
        if(method .equals( Method.POST)){
            FormBody.Builder formBuilder = new FormBody.Builder();
            for(String key : keys){
                String value = params.get(key);
                formBuilder.add(key, value);
            }
            builder.method(method.toString(), formBuilder.build());
        }else{
            url += "?";
            for(String key : keys){
                Object value = params.get(key);
                url += key +"="+value+"&";
            }
            url = url.substring(0, url.length() - 1);
        }

        builder = builder.url(url);
        return builder.build();
    }

    private static JSONObject getResponseObj(Response response){
        try {
            return new JSONObject(response.body().string());
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void get(String url, HashMap<String, String> params, final NewCallback newCallback){
        Request request = getBuilder(url, params, Method.GET);
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Error error = error("-1", e.getMessage());
                newCallback.onError(error);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JSONObject resultObj = getResponseObj(response);
                if(response.code() == 200){
                    newCallback.onSuccess(resultObj);
                }else{
                    Error error = gson.fromJson(resultObj.toString(), Error.class);
                    newCallback.onError(error);
                }
            }
        });
    }

    private static Error error(String code, String errorMsg){
        Error error = new Error();
        error.setError_code(code);
        error.setError(errorMsg);
        return error;
    }

}
